package in.muton.edushare.components.messaging.api;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.auth.api.Authentication;
import in.muton.edushare.common.VOHelper;
import in.muton.edushare.wicket.models.CayenneModel;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.OutgoingEmailsDAO;
import com.edushare.common.mailer.SchCancel;
import com.edushare.common.mailer.Schedule;
import com.edushare.common.vo.Schedules;
import com.edushare.common.vo.Users;

public class ScheduleMessage extends Message {

	public ScheduleMessage(Schedules sch, String oldTitle, String schType) {
		this.newSch = new CayenneModel<Schedules>(sch);
		this.schType = schType;
		oldSchName = oldTitle;
	}

	public ScheduleMessage(Schedules sch, String schType) {
		this.newSch = new CayenneModel<Schedules>(sch);
		this.schType = schType;
		if (schType == EVT_MODIFY || schType == EVT_CANCELLED) {
			setReciever(VOHelper.getFromTypeId(sch.getCreatorType(), sch
					.getSchCreator()));
			setPrivacy(sch.getSchType());
		}
	}

	@Override
	protected String getMessage() {
		if (schType.compareTo(EVT_CANCELLED) == 0
				|| schType.compareTo(NEW_EVENT) == 0) {
			return "<<<EDUSHAREMESSAGINGMETADATA:SCHEDULE:" + schType + ":"
					+ newSch.getObject().getSchId() + ":>>>";
		} else {
			return "<<<EDUSHAREMESSAGINGMETADATA:SCHEDULE:" + schType + ":"
					+ newSch.getObject().getSchId() + ":" + oldSchName + ">>>";
		}
	}

	private IModel<Schedules> newSch = null;
	private String schType = "";
	public String oldSchName = "";
	public final static String NEW_EVENT = "NEWEVENT";
	public final static String EVT_MODIFY = "EVT_CHANGE";
	public final static String EVT_CANCELLED = "EVT_CANCELLED";
	
	@Override
	protected void addditionalProcessing(Users u) {
		Authentication auth= new Authentication(u, EduShareSession.get().getLoggedInUser());
		if(auth.getSetting(Authentication.NOTIFY_EVT).equals("t")){
			if(schType.equals(NEW_EVENT)){
				new OutgoingEmailsDAO(EduShareSession.get().getSessionORMInterface()).
					sendMail(new Schedule(EduShareSession.get().getLoggedInUser(), u, newSch.getObject()).send());
			}else if(schType.equals(EVT_CANCELLED)){
				new OutgoingEmailsDAO(EduShareSession.get().getSessionORMInterface()).
				sendMail(new SchCancel(EduShareSession.get().getLoggedInUser(), u, newSch.getObject()).send());
			}	
		}
	}
}
